package com.toro.server.handler;

import com.toro.message.LoginRequestMessage;
import com.toro.message.LoginResponseMessage;
import com.toro.server.service.UserServiceFactory;
import com.toro.dao.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: LoginRequestMessageHandler
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/11 17:50
 */
@Slf4j
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage loginRequestMessage) throws Exception {
        log.info("接收到的登录请求:{}", loginRequestMessage);
        String username = loginRequestMessage.getUsername();
        String password = loginRequestMessage.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage message;
        if (login) {
            SessionFactory.getSession().bind(channelHandlerContext.channel(), username);
            message = new LoginResponseMessage(true, "登陆成功");
        } else {
            message = new LoginResponseMessage(false, "登陆失败,用户名或密码错误");
        }
        log.info("登录请求响应:{}", message);
        channelHandlerContext.writeAndFlush(message);
    }
}
